﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using StampController.BL;
using StampController.BL.Models;

namespace StampController.Pages
{
    public partial class Default : BasePage
    {
        private const int PageSize = 20;

        [WebMethod]
        public static object GetApprovalList(string status, int pageNum, string keyword)
        {
            var user = SessionUtils.Get<UsersModel>("USER");

            if (user.DeptID != null)
            {
                int count, countPending, countApproval, countDeleted;
                var im = new RequestFormImpl();
                var depts = new List<int>();
                if(user.IsHOD | user.IsGD) depts.Add(user.DeptID.Value); //lay dept cua user login
                depts = GetDepts(user.UserID, depts); //lay dept cua user da delegate
                var list = im.GetRequestFormList(user.UserID, depts, status, keyword, null, null, pageNum,
                    PageSize, out count, out countPending, out countApproval, out countDeleted);

                var obj = new GridTable<RequestFormModel>
                {
                    PageNum = pageNum,
                    RowCount = count,
                    PageSize = PageSize,
                    List = list,
                    Status = status.ToLower(),
                    Approval = true
                };

                return obj;
            }

            throw new ArgumentNullException();
        }

        private static List<int> GetDepts(string userId, List<int> depts)
        {
            var imAuthorized = new AuthorizedHistoryImpl();
            var users = imAuthorized.GetAuthorizedPersonList(userId, DateTime.Now);
            depts.AddRange(users.Where(x => x.IsGD | x.IsHOD).Select(x => x.DeptID != null ? x.DeptID.Value : 0)); // Only get the approval dept
            return depts;
        }
    }
}